package com.simba.server.framedecoder.decoders;

import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;

import com.simba.common.frameserver.FrameChannelManager;
import com.simba.common.utils.StringUtil;
import com.simba.server.components.*;
import com.simba.server.components.data.SorterInfo;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import com.simba.common.decoder.Decoder;
import com.simba.common.log.LogUtil;
import com.simba.common.utils.FrameUtils;
import com.simba.server.components.data.SlotInfo;
import com.simba.server.components.data.SortInfo;

public class PacketOffDecoder implements Decoder
{
	private static class PacketOffDecoderHolder
	{
		private static final PacketOffDecoder INSTANCE = new PacketOffDecoder();
	}

	public static final String NAME = "PacketOff";
	protected final static Logger logger = Logger.getLogger(PacketOffDecoder.class);

	private static final int SORTER_NUM_POSITION = 3;
	private static final int PACKET_OFF_SLOT_POSITION = 5;
	private static final int STR_CONTENT_BEGIN_POSITION = 6;
	private static final int STR_CONTENT_END_POSITION = 2;
	private static final int PLC_LEN = 17;
	private static final int PLC_POSITION = 0;

	public static PacketOffDecoder getDecoderInstance()
	{
		return PacketOffDecoderHolder.INSTANCE;
	}

	private PacketOffDecoder()
	{

	}

	@Override
	public void doDecode(Channel channel, Object message)
	{
		String plcId = "";
		try
		{
			ChannelsManager.getInstance().updateClient(channel);

			byte[] content = (byte[]) message;
			LogUtil.LogInfo(logger,"收到plc来的落格报文"+ StringUtil.byteToHexString(content));
			int sorterID = FrameUtils.getInstance().getUnsignedShortBigEndian(SORTER_NUM_POSITION, content);
			SorterInfo wheelSorterInfo = SorterManager.getInstance().getWheelSorterByID(String.valueOf(sorterID));
			if (wheelSorterInfo == null)
			{
				LogUtil.LogError(logger, "[WheelPacketOffDecoder] Sorter not found! Sorter ID:" + sorterID);
				return;
			}

			int droppedSlotId = content[PACKET_OFF_SLOT_POSITION] & 0xFF;

			// 10#
			int contentLen = content.length;
			String strContent = new String(content, STR_CONTENT_BEGIN_POSITION, contentLen - STR_CONTENT_END_POSITION - STR_CONTENT_BEGIN_POSITION, StandardCharsets.UTF_8);

			plcId = strContent.substring(PLC_POSITION, PLC_LEN);

			SortInfo wheelSortInfo = SortInfoManager.getInstance().getSortInfo(plcId);
			if (wheelSortInfo == null)
			{
				LogUtil.LogError(logger, "[WheelPacketOffDecoder] PacketOn info not found! PLC ID:" + plcId);
				return;

			}
			wheelSortInfo.setDroppedSlotId(droppedSlotId);
			wheelSortInfo.setErrorCodePLC(wheelSortInfo.getErrorCodeSVR());
			if (!wheelSortInfo.getSlotsList().contains(droppedSlotId)){
				wheelSortInfo.setErrorCodePLC(SortCommonDefines.ERROR_CODE_8_IBB_ERROR);
			}

			SlotInfo slotInfo = SlotManager.getInstance().getSlotInfo(String.valueOf(droppedSlotId));
			if (slotInfo != null)
			{
				if(wheelSortInfo.getErrorCodePLC()!=0){
					slotInfo.setArriveCode("00000000");
					slotInfo.setSlotName("收容格口");
				}else {
					slotInfo.setArriveCode(wheelSortInfo.getRoadSlot());
					slotInfo.setSlotName(wheelSortInfo.getRoadSlotName());
				}

				slotInfo.setTotalMailCount(slotInfo.getTotalMailCount() + 1);
				slotInfo.setCurrentMailCount(slotInfo.getCurrentMailCount() + 1);

				wheelSortInfo.setBoxCode(slotInfo.getBoxInfo().getBoxCode());
				wheelSortInfo.setSlotDistrict(slotInfo.getSlotDistrict());
			}

			Timestamp droppedTime = SortProtocolCreator.getInstance().createCurrentTimeStamp();
			wheelSortInfo.setTimestampPacketOff(droppedTime);
			wheelSortInfo.setTimePacketOff(droppedTime.toString());
			LogUtil.LogInfo(logger,"收到plc落格返回LKHC文,条码是"+ wheelSortInfo.getBarcodeList()+"下落格口是"+wheelSortInfo.getDroppedSlotId()+"报文"+StringUtil.byteToHexString(content));

			SortControllerManager.getInstance().onPacketOffMessage(wheelSortInfo);

			FrameChannelManager.getInstance().commitResponse(channel, content, false);
		}
		catch (Exception ex)
		{
			LogUtil.LogError(PacketOffDecoder.logger,
					"Catch an exception in PacketOff:" + ex.getMessage());
		}
		finally
		{
			SortInfoManager.getInstance().removeSortInfo(plcId);
		}
	}

	@Override
	public String getName()
	{
		return PacketOffDecoder.NAME;
	}
}
